/*
 * File: exercise3.cpp
 * -------------------
 * substr(str,pos,n) function 
 * compile command :
 * g++ -Wall -g exercise3.cpp -o exercise3 -lStanfordCPPLib -I ../include/
 */

#include <iostream>
#include <string>
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

string substr(string str, int pos, int n = -1);

int main()
{
	string str = "Hello Archlinux";
	cout<<substr(str, 3, 5)<<endl;
	cout<<substr(str, 3, 15)<<endl;
	cout<<substr(str, 3)<<endl;
	cout<<substr(str, 30, 2)<<endl;
	cout<<substr(str, 3)<<endl;
	return 0;
}

string substr(string str, int pos, int n )
{
	int nchars = str.length();
	string substring;
	if(pos > nchars)
	{
		error("pos is greater than the length of str.");
	}
	if(n == -1 || pos+n >nchars)
	{
		for(int i = pos; i < nchars; i++)
		{	
			substring += str[i];
		}
	}
	else
	{
		for(int i = 0; i < n ; i++)
		{	
			substring += str[pos+i];
		}
	}
	return substring;
}
